from flask import request, redirect, url_for, g
import re

from application import app
from common.libs.UserSerivice import UserService
from common.libs.logservice import LogService
from web.models.user import User


def check_login():
    """判断用户是否登录"""
    cookie = request.cookies
    auth_key = app.config["AUTH_COOKIE_NAME"]  # food
    auth_cookie = cookie[auth_key] if auth_key in cookie else ""
    # print(auth_cookie) #7d267998aa49e9c8a130f6a6b23763dc#1
    if auth_cookie is None:
        return False  # False表示没有登录
    auth_info = auth_cookie.split("#")
    if len(auth_info) != 2:
        return False
    try:
        user_info = User.query.filter_by(uid=auth_info[1]).first()
    except:
        return False
    if user_info is None:
        return False
    # 判断密钥
    authcode = UserService.genAuthCode(user_info)
    if auth_info[0] != authcode:
        return False
    return user_info


@app.before_request
def before_request():
    """拦截器-钩子函数，每次发送请求执行视图函数之前调用-- 用于验证用户是否已经登录"""
    path = request.path
    # 忽略的请求--有些请求(url)不需要做登录验证
    ignore_urls = app.config["IGNORE_URLS"]
    ignore_check_login_urls = app.config["IGNORE_CHECK_LOGIN_URLS"]
    # 小程序端的请求接口前缀
    API_IGNORE_URLS = app.config["API_IGNORE_URLS"]
    # 忽略的url
    ignore_merge = ignore_urls + ignore_check_login_urls+API_IGNORE_URLS  #
    print('忽略的路由：', ignore_merge)
    # 忽略的url 做成 re的 忽略编译模式
    pattern = re.compile("|".join(ignore_merge))
    if pattern.match(path):
        return None  # return None不做拦截
    user_info = check_login()  # 登录校验
    if not user_info:  # 没有登录
        return redirect(url_for('user_page.login'))
    # 用户已经登录,把当前登录的用户对象放到G对象中，以便全局引用
    g.current_user = user_info
    # 调用访问日志的方法，实现日志写入到数据表中
    LogService.addAccesslog()
    return None  # return None不做拦截
